
Namespace Xml
  ''' <summary>
  ''' Helper functions for XML.
  ''' </summary>
  ''' <remarks></remarks>
  Public NotInheritable Class XmlHelper

    ''' <summary>
    ''' Gets the node value.
    ''' </summary>
    ''' <param name="xml">The XML.</param>
    ''' <param name="path">The path.</param>
    ''' <returns></returns>
    Overloads Shared Function GetNodeValue(ByVal xml As System.Xml.XPath.IXPathNavigable, ByVal path As String) As String

      If IsNothing(xml) Then
        Throw New ArgumentNullException("xml")
      End If

      If String.IsNullOrEmpty(path) Then
        Throw New ArgumentNullException("path")
      End If

      Try
        Return xml.CreateNavigator.SelectSingleNode(path).Value
      Catch exNull As NullReferenceException
        Return String.Empty
      End Try

    End Function

    ''' <summary>
    ''' Gets the node value.
    ''' </summary>
    ''' <param name="xml">The XML.</param>
    ''' <param name="path">The path.</param>
    ''' <param name="fixForSql">if set to <c>true</c> [fix for SQL].</param>
    ''' <returns></returns>
    Overloads Shared Function GetNodeValue(ByVal xml As System.Xml.XPath.IXPathNavigable, ByVal path As String, ByVal fixForSql As Boolean) As String

      If IsNothing(xml) Then
        Throw New ArgumentNullException("xml")
      End If

      Try
        If fixForSql Then
          Return StringHelper.SQLEncode(xml.CreateNavigator.SelectSingleNode(path).Value)
        Else
          Return xml.CreateNavigator.SelectSingleNode(path).Value
        End If
      Catch exNull As NullReferenceException
        Return String.Empty
      End Try
    End Function

    ''' <summary>
    ''' Deserializes the specified input.
    ''' </summary>
    ''' <typeparam name="T"></typeparam>
    ''' <param name="input">The input.</param>
    ''' <returns></returns>
    Public Shared Function Deserialize(Of T)(ByVal input As String) As T
      Dim serializer As New System.Xml.Serialization.XmlSerializer(GetType(T))

      Return DirectCast(serializer.Deserialize(New System.Xml.XmlTextReader(New System.IO.StringReader(input))), T)

    End Function

    ''' <summary>
    ''' Serializes the specified input.
    ''' </summary>
    ''' <param name="input">The input.</param>
    ''' <returns></returns>
    Public Shared Function Serialize(ByVal input As Object) As String
      Dim returnXml As String = String.Empty
      Dim serializer As New System.Xml.Serialization.XmlSerializer(input.GetType)

      Using writer As New System.IO.StringWriter(CultureInfo.CurrentCulture)
        serializer.Serialize(New System.Xml.XmlTextWriter(writer), input)
        returnXml = writer.ToString()
      End Using

      Return returnXml

    End Function

    Private Sub New()
    End Sub

  End Class
End Namespace